package com.duqc.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;

/**
 * @ClassName FileChannelDemo
 * @Description 文件管道（分散读取 聚合写入）
 * @Author duqc
 * @Date 2021/8/23
 **/
public class FileChannelGatheringAndScatteringDemo {

    public static void main(String[] args) throws Exception {
        //获取文件输入流
        File file = new File("highgo.docx");
        FileInputStream inputStream = new FileInputStream(file);
        //从文件输入流获取通道
        FileChannel inputStreamChannel = inputStream.getChannel();
        //获取文件输出流
        FileOutputStream outputStream = new FileOutputStream("highgo1.docx");
        //从文件输出流获取通道
        FileChannel outputStreamChannel = outputStream.getChannel();
        //创建缓冲区
        ByteBuffer byteBuffer1 = ByteBuffer.allocate(5);
        ByteBuffer byteBuffer2 = ByteBuffer.allocate(5);
        ByteBuffer byteBuffer3 = ByteBuffer.allocate(5);
        //创建缓冲区数组
        ByteBuffer[] byteBuffers = {byteBuffer1, byteBuffer2, byteBuffer3};
        //循环写入到buffer缓冲区数组中，分散读取
        long read;
        long sumLength = 0;
        while ((read = inputStreamChannel.read(byteBuffers)) != -1) {
            sumLength += read;
            Arrays.stream(byteBuffers)
                    .map(byteBuffer -> "possion=" + byteBuffer.position() + ",limit=" + byteBuffer.limit())
                    .forEach(System.out::println);
            //切换模式
            Arrays.stream(byteBuffers).forEach(Buffer::flip);
            //聚合写入到输出流通道
            outputStreamChannel.write(byteBuffers);
            //清空缓冲区
            Arrays.stream(byteBuffers).forEach(Buffer::clear);
        }
        System.out.println("总长度：" + sumLength);

        //关闭通道
        outputStream.close();
        outputStreamChannel.close();
        inputStream.close();
        inputStreamChannel.close();
    }

}
